package com.itheima.easy.handler.aliyun;

import cn.hutool.core.util.StrUtil;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.itheima.easy.config.alipay.AliPayConfig;
import com.itheima.easy.constant.TradeConstant;
import com.itheima.easy.handler.PayNotifyHandler;
import com.itheima.easy.utils.EmptyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName AliNotifyHandler.java
 * @Description 支付通知接口
 */
@Component
public class AliPayNotifyHandler implements PayNotifyHandler {

    @Autowired
    AliPayConfig aliPayConfig;

    @Override
    public String notify(HttpServletRequest request, HttpEntity<String> httpEntity) {
        //获取参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, String> paramMap = new HashMap<>();
        for (String key : parameterMap.keySet()) {
            paramMap.put(key, parameterMap.get(key)[0]);
        }
        try {
            //1、获得支付宝配置文件
            Config config = aliPayConfig.config();
            //2、配置如果为空，抛出异常
            if (EmptyUtil.isNullOrEmpty(config)){
                throw new RuntimeException("阿里云支付配置为空！");
            }
            //3、使用配置
            Factory.setOptions(config);
            //4、验证签名
            boolean verifyResult = Factory.Payment.Common().verifyNotify(paramMap);
            if (!verifyResult) {
                return "verify sign fail";
            }
            //5、校验支付状态
            if (TradeConstant.ALI_TRADE_SUCCESS.equals(paramMap.get("trade_status"))) {
                return "success";
            }else {
                return "fail";
            }
        } catch (Exception e) {
            //6、异常返回 fail 给支付宝
            return "fail";
        }
    }
}
